function HeapOperator() {

}

HeapOperator.upAdjust = function(array) {
    var childIndex = array.length - 1;
    var parentIndex = Math.floor((childIndex - 1) / 2);
    // temp保存插入的叶子节点值，用于最后的赋值
    var temp = array[childIndex];
    while (childIndex > 0 && temp < array[parentIndex])
    {
        //无需真正交换，单向赋值即可
        array[childIndex] = array[parentIndex];
        childIndex = parentIndex;
        parentIndex = Math.floor((parentIndex - 1) / 2);
    }
    array[childIndex] = temp;
};

HeapOperator.downAdjust = function(array, parentIndex, length) {
    // temp保存父节点值，用于最后的赋值
    var temp = array[parentIndex];
    var childIndex = 2 * parentIndex + 1;
    while (childIndex < length) {
        // 如果有右孩子，且右孩子小于左孩子的值，则定位到右孩子
        if (childIndex + 1 < length && array[childIndex + 1] < array[childIndex]) {
            childIndex++;
        }
        // 如果父节点小于任何一个孩子的值，直接跳出
        if (temp <= array[childIndex]) {
            break;
        }

        //无需真正交换，单向赋值即可
        array[parentIndex] = array[childIndex];
        parentIndex = childIndex;
        childIndex = 2 * childIndex + 1;
    }
    array[parentIndex] = temp;
}

HeapOperator.buildHeap = function(array) {
    // 从最后一个非叶子节点开始，依次下沉调整
    for (var i = Math.floor((array.length - 2) / 2); i >= 0; i--) {
        HeapOperator.downAdjust(array, i, array.length);
    }
}

var array = new Array(1,3,2,6,5,7,8,9,10,0);
HeapOperator.upAdjust(array);
console.log(array);

array = new Array(7,1,3,10,5,2,8,9,6);
HeapOperator.buildHeap(array);
console.log(array);